LAB 4: Neighborhood Operations

Spatial Filtering

Exercise #1: We provide code template for performing neighborhood operations you have learned from the lecture. These include box filter, Gaussian blur, median filter, and Sobel edge operators. We show results on three images. Your task is to produce the same output on your selected image; only one input image is required. Your output should be a 3x3 grid (same ordering as an example), showing results of all operators; save it to a file Lab4Ex1.jpg. Explore different values for all variables and choose ones that best represent the results of your filters.

Image blurring using a box filter and a Gaussian kernel

Below we list OpenCV functions for box and Gaussian blur filter. You will need to set the value for ‘sz’ that is the width and the height of your box/Gaussian filter; the width and the height are equal for square filters.

In [ ]:
blurBox = cv2.boxFilter(im, -1, (sz,sz))
BlurGauss = cv2.GaussianBlur(im, (sz,sz), 0)

Median filter

We learn from the lecture that a median filter is effective in reducing impulse noise. To explore this effect, we first add salt-and-pepper noise to our image and then attempt to clean it. We compare how well a median filter does against that by a Gaussian blur. A function saltpepper_noise is provided here. Its parameter 'prob' is a probability, valued between 0 and 1, that specifies relatively how much noise is added. Try it and see what it does to an image.

In [ ]:
def saltpepper_noise(image, prob):
    output = np.zeros(image.shape,np.uint8)
    thres = 1 - prob
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = np.random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]
    return output
In [ ]:
imSP = saltpepper_noise(im,prob)         #Add noise, 'prob' controls how much noise is added
medianFiltered = cv2.medianBlur(im,sz)   #Apply a median filter to of size ‘sz’

Sobel edge detection

A Sobel filter can be set to detect either horizontal or vertical edges or both. These are set by the third and fourth parameters, which represents changes in the x- and the y-direction, respectively. We give you these settings for horizontal and vertical edges. You need to figure out how to set these variables to get edges in both directions at the same time (see example output). The last parameter, ksize, represents the size of your Sobel filter.

In [ ]:
sobeledgeH = cv2.Sobel(im, -1, 0, 1, ksize=sz)   #horizontal edges, changes in the y direction
sobeledgeV = cv2.Sobel(im, -1, 1, 0, ksize=sz)   #vertical edges, changes in the x direction

Example output on image #1

Example output on image #2

Example output on image #3

READY FOR SUBMISSION? Check your working directory, 6088xxx_lab4, it should now contained the following files. Please zip the folder and submit it to MyCourse.